<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 4.0.0">
  <link rel="icon" type="image/png" sizes="32x32" href="/img/favicon.ico">
  <link rel="icon" type="image/png" sizes="16x16" href="/img/favicon.ico">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib/font-awesome/css/font-awesome.min.css">


<script id="hexo-configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    hostname: new URL('https://cxyzjp.gitee.io').hostname,
    root: '/',
    scheme: 'Pisces',
    version: '7.6.0',
    exturl: true,
    sidebar: {"position":"left","display":"post","offset":12,"onmobile":true},
    copycode: {"enable":false,"show_result":false,"style":null},
    back2top: {"enable":true,"sidebar":false,"scrollpercent":true},
    bookmark: {"enable":false,"color":"#222","save":"auto"},
    fancybox: false,
    mediumzoom: true,
    lazyload: true,
    pangu: false,
    algolia: {
      appID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    },
    localsearch: {"enable":true,"trigger":"auto","top_n_per_article":1,"preload":true},
    path: 'search.json',
    motion: {"enable":false}
  };
</script>

  <meta name="description" content="刚接触Sharding-JDBC感觉挺新奇的，当时版本是1.x。后面公司需要使用Sharding-JDBC时版本已经是2.x了，不过不支持SpringBoot2.0会出现一些配置文件解析的问题，作者给出的回复是将在Sharding-JDBC3.x支持SpringBoot2.0。现在已经是4.x了，太快了吧。 ShardingSphere已经进入Apache孵化器，好的开源项目就是牛！ 记录一下当时">
<meta name="keywords" content="SpringBoot,Sharding-JDBC">
<meta property="og:type" content="article">
<meta property="og:title" content="SpringBoot集成Sharding-JDBC">
<meta property="og:url" content="https:&#x2F;&#x2F;cxyzjp.gitee.io&#x2F;SpringBoot&#x2F;ShardingJDBC&#x2F;index.html">
<meta property="og:site_name" content="程序员的日常">
<meta property="og:description" content="刚接触Sharding-JDBC感觉挺新奇的，当时版本是1.x。后面公司需要使用Sharding-JDBC时版本已经是2.x了，不过不支持SpringBoot2.0会出现一些配置文件解析的问题，作者给出的回复是将在Sharding-JDBC3.x支持SpringBoot2.0。现在已经是4.x了，太快了吧。 ShardingSphere已经进入Apache孵化器，好的开源项目就是牛！ 记录一下当时">
<meta property="og:locale" content="zh-CN">
<meta property="og:updated_time" content="2019-12-04T13:06:40.000Z">
<meta name="twitter:card" content="summary">

<link rel="canonical" href="https://cxyzjp.gitee.io/SpringBoot/ShardingJDBC/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome: false,
    isPost: true,
    isPage: false,
    isArchive: false
  };
</script>

  <title>SpringBoot集成Sharding-JDBC | 程序员的日常</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-meta">

    <div>
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">程序员的日常</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
        <h1 class="site-subtitle" itemprop="description">自强不息</h1>
      
  </div>

  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>
</div>


<nav class="site-nav">
  
  <ul id="menu" class="menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-fw fa-home"></i>首页</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-fw fa-archive"></i>归档<span class="badge">5</span></a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="fa fa-fw fa-tags"></i>标签<span class="badge">6</span></a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>

</nav>
  <div class="site-search">
    <div class="popup search-popup">
    <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocorrect="off" autocapitalize="none"
           placeholder="搜索..." spellcheck="false"
           type="text" id="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result"></div>

</div>
<div class="search-pop-overlay"></div>

  </div>
</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content">
            

  <div class="posts-expand">
      
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block " lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://cxyzjp.gitee.io/SpringBoot/ShardingJDBC/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/img/avatar.jpg">
      <meta itemprop="name" content="CXYZJP">
      <meta itemprop="description" content="记录生活中的点点滴滴">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="程序员的日常">
    </span>
      <header class="post-header">
        <h2 class="post-title" itemprop="name headline">
          SpringBoot集成Sharding-JDBC
        </h2>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2019-12-03 22:23:48" itemprop="dateCreated datePublished" datetime="2019-12-03T22:23:48+08:00">2019-12-03</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2019-12-04 21:06:40" itemprop="dateModified" datetime="2019-12-04T21:06:40+08:00">2019-12-04</time>
              </span>

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <p>刚接触Sharding-JDBC感觉挺新奇的，当时版本是1.x。后面公司需要使用Sharding-JDBC时版本已经是2.x了，不过不支持SpringBoot2.0会出现一些配置文件解析的问题，作者给出的回复是将在Sharding-JDBC3.x支持SpringBoot2.0。现在已经是4.x了，太快了吧。</p>
<p>ShardingSphere已经进入Apache孵化器，好的开源项目就是牛！</p>
<p>记录一下当时项目中集成Sharding-JDBC的过程。</p>
<a id="more"></a>

<h1 id="为什么要使用Sharding-JDBC"><a href="#为什么要使用Sharding-JDBC" class="headerlink" title="为什么要使用Sharding-JDBC"></a>为什么要使用Sharding-JDBC</h1><p>项目中会有持续快速增长的数据，在项目架构时考虑引入分库分表框架。 当时Mycat和Sharding-JDBC都比较流行。</p>
<h2 id="Mycat和Sharding-JDBC选型"><a href="#Mycat和Sharding-JDBC选型" class="headerlink" title="Mycat和Sharding-JDBC选型"></a>Mycat和Sharding-JDBC选型</h2><p>Mycat号称代码零侵入，但是会存在一些问题。<br>1.文档不是很友好<br>2.链路过长，每层都会增加响应时间<br>3.Proxy节点高可用问题<br>4.运维成本增加<br>…</p>
<p>Sharding-JDBC优点<br>1.官网文档特别详细<br>2.Java语言天生支持，轻量级<br>3.生态丰富，社区活跃<br>…</p>
<h1 id="集成Sharding-JDBC"><a href="#集成Sharding-JDBC" class="headerlink" title="集成Sharding-JDBC"></a>集成Sharding-JDBC</h1><p><span class="exturl" data-url="aHR0cHM6Ly9zaGFyZGluZ3NwaGVyZS5hcGFjaGUub3JnLw==" title="https://shardingsphere.apache.org/">官网<i class="fa fa-external-link"></i></span> 文档写得很详细，</p>
<h1 id="遇到的问题"><a href="#遇到的问题" class="headerlink" title="遇到的问题"></a>遇到的问题</h1><ol>
<li>不支持SpringBoot2.0的问题。（先是降到1.5，后又再升级回2.0）</li>
<li>分库分表较多的话，会造成yml文件特别大</li>
<li>同一数据源只支持所有都进行分片，即使是不需要分片的表。</li>
</ol>
<h1 id="采用多数据源方式"><a href="#采用多数据源方式" class="headerlink" title="采用多数据源方式"></a>采用多数据源方式</h1><p>Sharding-JDBC多数据源方式可以解决yml文件过大，部分数据库表需要分片的问题。</p>
<p>有primary-data-sources(不分片)和sharding-data-sources(分片)两个数据源</p>
<h2 id="yml配置"><a href="#yml配置" class="headerlink" title="yml配置"></a>yml配置</h2><figure class="highlight yml"><table><tr><td class="code"><pre><span class="line"><span class="attr">custom:</span></span></pre></td></tr><tr><td class="code"><pre><span class="line">  <span class="attr">jdbc:</span></span></pre></td></tr><tr><td class="code"><pre><span class="line">    <span class="attr">primary-data-sources:</span></span></pre></td></tr><tr><td class="code"><pre><span class="line">      <span class="attr">url:</span> <span class="string">jdbc:mysql://localhost:3306/cd?characterEncoding=UTF-8&amp;zeroDateTimeBehavior=convertToNull&amp;useSSL=false</span></span></pre></td></tr><tr><td class="code"><pre><span class="line">      <span class="attr">username:</span> <span class="string">root</span></span></pre></td></tr><tr><td class="code"><pre><span class="line">      <span class="attr">password:</span> <span class="string">root</span></span></pre></td></tr><tr><td class="code"><pre><span class="line">    <span class="attr">sharding:</span> <span class="literal">true</span></span></pre></td></tr><tr><td class="code"><pre><span class="line">    <span class="attr">sharding-data-sources:</span></span></pre></td></tr><tr><td class="code"><pre><span class="line">      <span class="attr">ds-order-seller-0:</span></span></pre></td></tr><tr><td class="code"><pre><span class="line">        <span class="attr">url:</span> <span class="string">jdbc:mysql://localhost:3306/cd_order_seller_0?characterEncoding=UTF-8&amp;zeroDateTimeBehavior=convertToNull&amp;useSSL=false</span></span></pre></td></tr><tr><td class="code"><pre><span class="line">        <span class="attr">username:</span> <span class="string">root</span></span></pre></td></tr><tr><td class="code"><pre><span class="line">        <span class="attr">password:</span> <span class="string">root</span></span></pre></td></tr><tr><td class="code"><pre><span class="line">      <span class="attr">ds-order-seller-1:</span></span></pre></td></tr><tr><td class="code"><pre><span class="line">        <span class="attr">url:</span> <span class="string">jdbc:mysql://localhost:3306/cd_order_seller_1?characterEncoding=UTF-8&amp;zeroDateTimeBehavior=convertToNull&amp;useSSL=false</span></span></pre></td></tr><tr><td class="code"><pre><span class="line">        <span class="attr">username:</span> <span class="string">root</span></span></pre></td></tr><tr><td class="code"><pre><span class="line">        <span class="attr">password:</span> <span class="string">root</span></span></pre></td></tr><tr><td class="code"><pre><span class="line">      <span class="attr">ds-order-user-0:</span></span></pre></td></tr><tr><td class="code"><pre><span class="line">        <span class="attr">url:</span> <span class="string">jdbc:mysql://localhost:3306/cd_order_user_0?characterEncoding=UTF-8&amp;zeroDateTimeBehavior=convertToNull&amp;useSSL=false</span></span></pre></td></tr><tr><td class="code"><pre><span class="line">        <span class="attr">username:</span> <span class="string">root</span></span></pre></td></tr><tr><td class="code"><pre><span class="line">        <span class="attr">password:</span> <span class="string">root</span></span></pre></td></tr><tr><td class="code"><pre><span class="line">      <span class="attr">ds-order-user-1:</span></span></pre></td></tr><tr><td class="code"><pre><span class="line">        <span class="attr">url:</span> <span class="string">jdbc:mysql://localhost:3306/cd_order_user_1?characterEncoding=UTF-8&amp;zeroDateTimeBehavior=convertToNull&amp;useSSL=false</span></span></pre></td></tr><tr><td class="code"><pre><span class="line">        <span class="attr">username:</span> <span class="string">root</span></span></pre></td></tr><tr><td class="code"><pre><span class="line">        <span class="attr">password:</span> <span class="string">root</span></span></pre></td></tr></table></figure>

<h2 id="数据源配置"><a href="#数据源配置" class="headerlink" title="数据源配置"></a>数据源配置</h2><h3 id="主数据源"><a href="#主数据源" class="headerlink" title="主数据源"></a>主数据源</h3><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">package</span> com.cd.orderpay.config;</span></pre></td></tr><tr><td class="code"><pre><span class="line"></span></pre></td></tr><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> com.cd.common.core.config.datasource.DataSourceConfig;</span></pre></td></tr><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> org.apache.ibatis.session.SqlSessionFactory;</span></pre></td></tr><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> org.mybatis.spring.SqlSessionFactoryBean;</span></pre></td></tr><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> org.mybatis.spring.SqlSessionTemplate;</span></pre></td></tr><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> org.mybatis.spring.annotation.MapperScan;</span></pre></td></tr><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> org.springframework.beans.factory.annotation.Qualifier;</span></pre></td></tr><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> org.springframework.context.annotation.Bean;</span></pre></td></tr><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> org.springframework.context.annotation.Configuration;</span></pre></td></tr><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> org.springframework.context.annotation.Primary;</span></pre></td></tr><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> org.springframework.core.io.support.PathMatchingResourcePatternResolver;</span></pre></td></tr><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> org.springframework.jdbc.datasource.DataSourceTransactionManager;</span></pre></td></tr><tr><td class="code"><pre><span class="line"></span></pre></td></tr><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> javax.sql.DataSource;</span></pre></td></tr><tr><td class="code"><pre><span class="line"></span></pre></td></tr><tr><td class="code"><pre><span class="line"><span class="meta">@Configuration</span></span></pre></td></tr><tr><td class="code"><pre><span class="line"><span class="meta">@MapperScan</span>(basePackages = <span class="string">"com.cd.*.mapper.normal"</span>, sqlSessionTemplateRef = <span class="string">"primarySqlSessionTemplate"</span>)</span></pre></td></tr><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">PrimaryDataSourceConfig</span> </span>&#123;</span></pre></td></tr><tr><td class="code"><pre><span class="line"></span></pre></td></tr><tr><td class="code"><pre><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> DataSourceConfig dataSourceConfig;</span></pre></td></tr><tr><td class="code"><pre><span class="line"></span></pre></td></tr><tr><td class="code"><pre><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">PrimaryDataSourceConfig</span><span class="params">(DataSourceConfig dataSourceConfig)</span> </span>&#123;</span></pre></td></tr><tr><td class="code"><pre><span class="line">        <span class="keyword">this</span>.dataSourceConfig = dataSourceConfig;</span></pre></td></tr><tr><td class="code"><pre><span class="line">    &#125;</span></pre></td></tr><tr><td class="code"><pre><span class="line"></span></pre></td></tr><tr><td class="code"><pre><span class="line">    <span class="meta">@Primary</span></span></pre></td></tr><tr><td class="code"><pre><span class="line">    <span class="meta">@Bean</span>(name = <span class="string">"primaryDataSource"</span>)</span></pre></td></tr><tr><td class="code"><pre><span class="line">    <span class="function"><span class="keyword">public</span> DataSource <span class="title">dataSource</span><span class="params">()</span> </span>&#123;</span></pre></td></tr><tr><td class="code"><pre><span class="line">        <span class="keyword">return</span> dataSourceConfig.buildPrimaryDataSources();</span></pre></td></tr><tr><td class="code"><pre><span class="line">    &#125;</span></pre></td></tr><tr><td class="code"><pre><span class="line"></span></pre></td></tr><tr><td class="code"><pre><span class="line">    <span class="meta">@Primary</span></span></pre></td></tr><tr><td class="code"><pre><span class="line">    <span class="meta">@Bean</span>(name = <span class="string">"primarySqlSessionFactory"</span>)</span></pre></td></tr><tr><td class="code"><pre><span class="line">    <span class="function"><span class="keyword">public</span> SqlSessionFactory <span class="title">sqlSessionFactory</span><span class="params">(</span></span></span></pre></td></tr><tr><td class="code"><pre><span class="line"><span class="function"><span class="params">            @Qualifier(<span class="string">"primaryDataSource"</span>)</span> DataSource dataSource) <span class="keyword">throws</span> Exception </span>&#123;</span></pre></td></tr><tr><td class="code"><pre><span class="line">        SqlSessionFactoryBean bean = <span class="keyword">new</span> SqlSessionFactoryBean();</span></pre></td></tr><tr><td class="code"><pre><span class="line">        bean.setDataSource(dataSource);</span></pre></td></tr><tr><td class="code"><pre><span class="line">        bean.setMapperLocations(<span class="keyword">new</span> PathMatchingResourcePatternResolver()</span></pre></td></tr><tr><td class="code"><pre><span class="line">                .getResources(<span class="string">"classpath*:mapper/normal/**/*.xml"</span>));</span></pre></td></tr><tr><td class="code"><pre><span class="line">        <span class="keyword">return</span> bean.getObject();</span></pre></td></tr><tr><td class="code"><pre><span class="line">    &#125;</span></pre></td></tr><tr><td class="code"><pre><span class="line"></span></pre></td></tr><tr><td class="code"><pre><span class="line">    <span class="meta">@Primary</span></span></pre></td></tr><tr><td class="code"><pre><span class="line">    <span class="meta">@Bean</span>(name = <span class="string">"primaryTransactionManager"</span>)</span></pre></td></tr><tr><td class="code"><pre><span class="line">    <span class="function"><span class="keyword">public</span> DataSourceTransactionManager <span class="title">transactionManager</span><span class="params">(</span></span></span></pre></td></tr><tr><td class="code"><pre><span class="line"><span class="function"><span class="params">            @Qualifier(<span class="string">"primaryDataSource"</span>)</span> DataSource dataSource) </span>&#123;</span></pre></td></tr><tr><td class="code"><pre><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> DataSourceTransactionManager(dataSource);</span></pre></td></tr><tr><td class="code"><pre><span class="line">    &#125;</span></pre></td></tr><tr><td class="code"><pre><span class="line"></span></pre></td></tr><tr><td class="code"><pre><span class="line">    <span class="meta">@Primary</span></span></pre></td></tr><tr><td class="code"><pre><span class="line">    <span class="meta">@Bean</span>(name = <span class="string">"primarySqlSessionTemplate"</span>)</span></pre></td></tr><tr><td class="code"><pre><span class="line">    <span class="function"><span class="keyword">public</span> SqlSessionTemplate <span class="title">sqlSessionTemplate</span><span class="params">(</span></span></span></pre></td></tr><tr><td class="code"><pre><span class="line"><span class="function"><span class="params">            @Qualifier(<span class="string">"primarySqlSessionFactory"</span>)</span> SqlSessionFactory sqlSessionFactory) </span>&#123;</span></pre></td></tr><tr><td class="code"><pre><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> SqlSessionTemplate(sqlSessionFactory);</span></pre></td></tr><tr><td class="code"><pre><span class="line">    &#125;</span></pre></td></tr><tr><td class="code"><pre><span class="line"></span></pre></td></tr><tr><td class="code"><pre><span class="line">&#125;</span></pre></td></tr></table></figure>

<h3 id="Sharding数据源"><a href="#Sharding数据源" class="headerlink" title="Sharding数据源"></a>Sharding数据源</h3><figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">package</span> com.cd.orderpay.config;</span></pre></td></tr><tr><td class="code"><pre><span class="line"></span></pre></td></tr><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> com.cd.common.core.config.datasource.DataSourceConfig;</span></pre></td></tr><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> com.cd.common.core.sharding.OrderUserDBShardingAlgorithm;</span></pre></td></tr><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> com.cd.common.core.sharding.OrderUserTBShardingAlgorithm;</span></pre></td></tr><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> io.shardingsphere.api.config.ShardingRuleConfiguration;</span></pre></td></tr><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> io.shardingsphere.api.config.TableRuleConfiguration;</span></pre></td></tr><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> io.shardingsphere.api.config.strategy.ComplexShardingStrategyConfiguration;</span></pre></td></tr><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> io.shardingsphere.Sharding-JDBC.api.ShardingDataSourceFactory;</span></pre></td></tr><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> org.apache.ibatis.session.SqlSessionFactory;</span></pre></td></tr><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> org.mybatis.spring.SqlSessionFactoryBean;</span></pre></td></tr><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> org.mybatis.spring.SqlSessionTemplate;</span></pre></td></tr><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> org.mybatis.spring.annotation.MapperScan;</span></pre></td></tr><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> org.springframework.beans.factory.annotation.Qualifier;</span></pre></td></tr><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;</span></pre></td></tr><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> org.springframework.context.annotation.Bean;</span></pre></td></tr><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> org.springframework.context.annotation.Configuration;</span></pre></td></tr><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> org.springframework.core.io.support.PathMatchingResourcePatternResolver;</span></pre></td></tr><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> org.springframework.jdbc.datasource.DataSourceTransactionManager;</span></pre></td></tr><tr><td class="code"><pre><span class="line"></span></pre></td></tr><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> javax.sql.DataSource;</span></pre></td></tr><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> java.sql.SQLException;</span></pre></td></tr><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> java.util.HashMap;</span></pre></td></tr><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> java.util.LinkedList;</span></pre></td></tr><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> java.util.Map;</span></pre></td></tr><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> java.util.Properties;</span></pre></td></tr><tr><td class="code"><pre><span class="line"></span></pre></td></tr><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> <span class="keyword">static</span> com.cd.common.core.sharding.ShardingUtils.*;</span></pre></td></tr><tr><td class="code"><pre><span class="line"></span></pre></td></tr><tr><td class="code"><pre><span class="line"><span class="meta">@Configuration</span></span></pre></td></tr><tr><td class="code"><pre><span class="line"><span class="meta">@ConditionalOnProperty</span>(name = <span class="string">"custom.jdbc.sharding"</span>, havingValue = <span class="string">"true"</span>)</span></pre></td></tr><tr><td class="code"><pre><span class="line"><span class="meta">@MapperScan</span>(basePackages = <span class="string">"com.cd.*.mapper.sharding"</span>, sqlSessionTemplateRef = <span class="string">"sqlSessionTemplate"</span>)</span></pre></td></tr><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">ShardingDataSourceConfig</span> </span>&#123;</span></pre></td></tr><tr><td class="code"><pre><span class="line"></span></pre></td></tr><tr><td class="code"><pre><span class="line">    <span class="keyword">private</span> LinkedList&lt;String&gt; bindingTableGroups = <span class="keyword">new</span> LinkedList&lt;&gt;();</span></pre></td></tr><tr><td class="code"><pre><span class="line">    <span class="keyword">private</span> LinkedList&lt;TableRuleConfiguration&gt; tableRules = <span class="keyword">new</span> LinkedList&lt;&gt;();</span></pre></td></tr><tr><td class="code"><pre><span class="line"></span></pre></td></tr><tr><td class="code"><pre><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> DataSourceConfig dataSourceConfig;</span></pre></td></tr><tr><td class="code"><pre><span class="line"></span></pre></td></tr><tr><td class="code"><pre><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">ShardingDataSourceConfig</span><span class="params">(DataSourceConfig dataSourceConfig)</span> </span>&#123;</span></pre></td></tr><tr><td class="code"><pre><span class="line">        <span class="keyword">this</span>.dataSourceConfig = dataSourceConfig;</span></pre></td></tr><tr><td class="code"><pre><span class="line">    &#125;</span></pre></td></tr><tr><td class="code"><pre><span class="line"></span></pre></td></tr><tr><td class="code"><pre><span class="line">    <span class="meta">@Bean</span></span></pre></td></tr><tr><td class="code"><pre><span class="line">    <span class="function"><span class="keyword">public</span> DataSource <span class="title">dataSource</span><span class="params">()</span> <span class="keyword">throws</span> SQLException </span>&#123;</span></pre></td></tr><tr><td class="code"><pre><span class="line">        Map&lt;String, DataSource&gt; dataSourceMap = dataSourceConfig.buildShardingDataSources();</span></pre></td></tr><tr><td class="code"><pre><span class="line">        buildTableRuleConfig(dataSourceMap);</span></pre></td></tr><tr><td class="code"><pre><span class="line"></span></pre></td></tr><tr><td class="code"><pre><span class="line">        ShardingRuleConfiguration shardingRuleConfig = <span class="keyword">new</span> ShardingRuleConfiguration();</span></pre></td></tr><tr><td class="code"><pre><span class="line">        shardingRuleConfig.setTableRuleConfigs(tableRules);</span></pre></td></tr><tr><td class="code"><pre><span class="line">        shardingRuleConfig.setBindingTableGroups(bindingTableGroups);</span></pre></td></tr><tr><td class="code"><pre><span class="line"></span></pre></td></tr><tr><td class="code"><pre><span class="line">        <span class="keyword">return</span> ShardingDataSourceFactory.createDataSource(dataSourceMap, shardingRuleConfig, <span class="keyword">new</span> HashMap&lt;&gt;(), buildProperties());</span></pre></td></tr><tr><td class="code"><pre><span class="line">    &#125;</span></pre></td></tr><tr><td class="code"><pre><span class="line"></span></pre></td></tr><tr><td class="code"><pre><span class="line">    <span class="meta">@Bean</span>(name = <span class="string">"sqlSessionFactory"</span>)</span></pre></td></tr><tr><td class="code"><pre><span class="line">    <span class="function"><span class="keyword">public</span> SqlSessionFactory <span class="title">sqlSessionFactory</span><span class="params">(@Qualifier(<span class="string">"dataSource"</span>)</span> DataSource dataSource) <span class="keyword">throws</span> Exception </span>&#123;</span></pre></td></tr><tr><td class="code"><pre><span class="line">        SqlSessionFactoryBean bean = <span class="keyword">new</span> SqlSessionFactoryBean();</span></pre></td></tr><tr><td class="code"><pre><span class="line">        bean.setDataSource(dataSource);</span></pre></td></tr><tr><td class="code"><pre><span class="line">        bean.setMapperLocations(<span class="keyword">new</span> PathMatchingResourcePatternResolver()</span></pre></td></tr><tr><td class="code"><pre><span class="line">                .getResources(<span class="string">"classpath*:mapper/sharding/**/*.xml"</span>));</span></pre></td></tr><tr><td class="code"><pre><span class="line">        <span class="keyword">return</span> bean.getObject();</span></pre></td></tr><tr><td class="code"><pre><span class="line">    &#125;</span></pre></td></tr><tr><td class="code"><pre><span class="line"></span></pre></td></tr><tr><td class="code"><pre><span class="line">    <span class="meta">@Bean</span>(name = <span class="string">"transactionManager"</span>)</span></pre></td></tr><tr><td class="code"><pre><span class="line">    <span class="function"><span class="keyword">public</span> DataSourceTransactionManager <span class="title">transactionManager</span><span class="params">(@Qualifier(<span class="string">"dataSource"</span>)</span> DataSource dataSource) </span>&#123;</span></pre></td></tr><tr><td class="code"><pre><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> DataSourceTransactionManager(dataSource);</span></pre></td></tr><tr><td class="code"><pre><span class="line">    &#125;</span></pre></td></tr><tr><td class="code"><pre><span class="line"></span></pre></td></tr><tr><td class="code"><pre><span class="line">    <span class="meta">@Bean</span>(name = <span class="string">"sqlSessionTemplate"</span>)</span></pre></td></tr><tr><td class="code"><pre><span class="line">    <span class="function"><span class="keyword">public</span> SqlSessionTemplate <span class="title">sqlSessionTemplate</span><span class="params">(@Qualifier(<span class="string">"sqlSessionFactory"</span>)</span> SqlSessionFactory sqlSessionFactory) </span>&#123;</span></pre></td></tr><tr><td class="code"><pre><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> SqlSessionTemplate(sqlSessionFactory);</span></pre></td></tr><tr><td class="code"><pre><span class="line">    &#125;</span></pre></td></tr><tr><td class="code"><pre><span class="line"></span></pre></td></tr><tr><td class="code"><pre><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">buildTableRuleConfig</span><span class="params">(Map&lt;String, DataSource&gt; dataSourceMap)</span> </span>&#123;</span></pre></td></tr><tr><td class="code"><pre><span class="line">        <span class="comment">// 订单相关，卖家维度</span></span></pre></td></tr><tr><td class="code"><pre><span class="line">        <span class="keyword">if</span> (dataSourceMap.get(<span class="string">"ds-order-seller-0"</span>) != <span class="keyword">null</span>) &#123;</span></pre></td></tr><tr><td class="code"><pre><span class="line">            <span class="comment">//  订单表，卖家维度</span></span></pre></td></tr><tr><td class="code"><pre><span class="line">            doubleKeyTableRule(<span class="string">"ds-order-seller"</span>, <span class="string">"order_seller"</span>, <span class="string">"store_sn"</span>, <span class="string">"order_sn"</span>);</span></pre></td></tr><tr><td class="code"><pre><span class="line"></span></pre></td></tr><tr><td class="code"><pre><span class="line">            <span class="comment">// bindingTableGroups.add("order_pay_seller,order_pay_poundage");</span></span></pre></td></tr><tr><td class="code"><pre><span class="line">        &#125;</span></pre></td></tr><tr><td class="code"><pre><span class="line"></span></pre></td></tr><tr><td class="code"><pre><span class="line">        <span class="comment">// 订单相关，买家维度</span></span></pre></td></tr><tr><td class="code"><pre><span class="line">        <span class="keyword">if</span> (dataSourceMap.get(<span class="string">"ds-order-user-0"</span>) != <span class="keyword">null</span>) &#123;</span></pre></td></tr><tr><td class="code"><pre><span class="line">            <span class="comment">//  订单表，买家维度</span></span></pre></td></tr><tr><td class="code"><pre><span class="line">            userAndOrderTableRule(<span class="string">"ds-order-user"</span>, <span class="string">"order_user"</span>);</span></pre></td></tr><tr><td class="code"><pre><span class="line">        &#125;</span></pre></td></tr><tr><td class="code"><pre><span class="line">    &#125;</span></pre></td></tr><tr><td class="code"><pre><span class="line"></span></pre></td></tr><tr><td class="code"><pre><span class="line">    <span class="function"><span class="keyword">private</span> Properties <span class="title">buildProperties</span><span class="params">()</span> </span>&#123;</span></pre></td></tr><tr><td class="code"><pre><span class="line">        Properties props = <span class="keyword">new</span> Properties();</span></pre></td></tr><tr><td class="code"><pre><span class="line">        props.setProperty(<span class="string">"sql.show "</span>, <span class="string">"true"</span>);</span></pre></td></tr><tr><td class="code"><pre><span class="line">        <span class="keyword">return</span> props;</span></pre></td></tr><tr><td class="code"><pre><span class="line">    &#125;</span></pre></td></tr><tr><td class="code"><pre><span class="line"></span></pre></td></tr><tr><td class="code"><pre><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">doubleKeyTableRule</span><span class="params">(String datasource, String logicTable, String key1, String key2)</span> </span>&#123;</span></pre></td></tr><tr><td class="code"><pre><span class="line">        TableRuleConfiguration tableRule = <span class="keyword">new</span> TableRuleConfiguration();</span></pre></td></tr><tr><td class="code"><pre><span class="line">        tableRule.setLogicTable(logicTable);</span></pre></td></tr><tr><td class="code"><pre><span class="line">        tableRule.setActualDataNodes(datasource + <span class="string">"-$-&gt;&#123;0..7&#125;."</span> + logicTable + <span class="string">"_$-&gt;&#123;0..7&#125;"</span>);</span></pre></td></tr><tr><td class="code"><pre><span class="line">        tableRule.setDatabaseShardingStrategyConfig(doubleKeyDBSharding(key1, key2));</span></pre></td></tr><tr><td class="code"><pre><span class="line">        tableRule.setTableShardingStrategyConfig(doubleKeyTBSharding(key1, key2));</span></pre></td></tr><tr><td class="code"><pre><span class="line">        tableRules.add(tableRule);</span></pre></td></tr><tr><td class="code"><pre><span class="line">    &#125;</span></pre></td></tr><tr><td class="code"><pre><span class="line"></span></pre></td></tr><tr><td class="code"><pre><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">userAndOrderTableRule</span><span class="params">(String datasource, String logicTable)</span> </span>&#123;</span></pre></td></tr><tr><td class="code"><pre><span class="line">        TableRuleConfiguration tableRule = <span class="keyword">new</span> TableRuleConfiguration();</span></pre></td></tr><tr><td class="code"><pre><span class="line">        tableRule.setLogicTable(logicTable);</span></pre></td></tr><tr><td class="code"><pre><span class="line">        tableRule.setActualDataNodes(datasource + <span class="string">"-$-&gt;&#123;0..7&#125;."</span> + logicTable + <span class="string">"_$-&gt;&#123;0..7&#125;"</span>);</span></pre></td></tr><tr><td class="code"><pre><span class="line">        tableRule.setDatabaseShardingStrategyConfig(</span></pre></td></tr><tr><td class="code"><pre><span class="line">                <span class="keyword">new</span> ComplexShardingStrategyConfiguration(<span class="string">"user_sn,order_sn"</span>, <span class="keyword">new</span> OrderUserDBShardingAlgorithm()));</span></pre></td></tr><tr><td class="code"><pre><span class="line">        tableRule.setTableShardingStrategyConfig(</span></pre></td></tr><tr><td class="code"><pre><span class="line">                <span class="keyword">new</span> ComplexShardingStrategyConfiguration(<span class="string">"user_sn,order_sn"</span>, <span class="keyword">new</span> OrderUserTBShardingAlgorithm()));</span></pre></td></tr><tr><td class="code"><pre><span class="line">        tableRules.add(tableRule);</span></pre></td></tr><tr><td class="code"><pre><span class="line">    &#125;</span></pre></td></tr><tr><td class="code"><pre><span class="line">&#125;</span></pre></td></tr></table></figure>

<h2 id="部分工具类"><a href="#部分工具类" class="headerlink" title="部分工具类"></a>部分工具类</h2><p>BaseShardingAlgorithm.java</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">package</span> com.cd.common.core.sharding;</span></pre></td></tr><tr><td class="code"><pre><span class="line"></span></pre></td></tr><tr><td class="code"><pre><span class="line"><span class="comment">/**</span></span></pre></td></tr><tr><td class="code"><pre><span class="line"><span class="comment"> * description: 分片策略</span></span></pre></td></tr><tr><td class="code"><pre><span class="line"><span class="comment"> * author: bowen</span></span></pre></td></tr><tr><td class="code"><pre><span class="line"><span class="comment"> *  １、中间变量　＝ user_id%（库数量*每个库的表数量）;</span></span></pre></td></tr><tr><td class="code"><pre><span class="line"><span class="comment"> *  ２、库序号　＝　取整（中间变量／每个库的表数量）;</span></span></pre></td></tr><tr><td class="code"><pre><span class="line"><span class="comment"> *  ３、表序号　＝　中间变量％每个库的表数量;</span></span></pre></td></tr><tr><td class="code"><pre><span class="line"><span class="comment"> */</span></span></pre></td></tr><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">BaseShardingAlgorithm</span> </span>&#123;</span></pre></td></tr><tr><td class="code"><pre><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">int</span> dbNum = <span class="number">8</span>;</span></pre></td></tr><tr><td class="code"><pre><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">int</span> tbNum = <span class="number">8</span>;</span></pre></td></tr><tr><td class="code"><pre><span class="line"></span></pre></td></tr><tr><td class="code"><pre><span class="line">    <span class="function"><span class="keyword">int</span> <span class="title">getLast4</span><span class="params">(Object o)</span> </span>&#123;</span></pre></td></tr><tr><td class="code"><pre><span class="line">        String s = o.toString();</span></pre></td></tr><tr><td class="code"><pre><span class="line">        <span class="keyword">if</span>(s.length() &lt;= <span class="number">4</span>)&#123;</span></pre></td></tr><tr><td class="code"><pre><span class="line">            <span class="keyword">return</span> Integer.valueOf(s);</span></pre></td></tr><tr><td class="code"><pre><span class="line">        &#125;</span></pre></td></tr><tr><td class="code"><pre><span class="line">        String last4 = s.substring(s.length() - <span class="number">4</span>);</span></pre></td></tr><tr><td class="code"><pre><span class="line">        <span class="keyword">return</span> Integer.valueOf(last4);</span></pre></td></tr><tr><td class="code"><pre><span class="line">    &#125;</span></pre></td></tr><tr><td class="code"><pre><span class="line"></span></pre></td></tr><tr><td class="code"><pre><span class="line">    <span class="function">String <span class="title">getDBIndex</span><span class="params">(<span class="keyword">int</span> v)</span> </span>&#123;</span></pre></td></tr><tr><td class="code"><pre><span class="line">        <span class="keyword">int</span> m = v % (dbNum * tbNum);</span></pre></td></tr><tr><td class="code"><pre><span class="line">        <span class="keyword">int</span> d = m / tbNum;</span></pre></td></tr><tr><td class="code"><pre><span class="line">        <span class="keyword">return</span> String.valueOf(d);</span></pre></td></tr><tr><td class="code"><pre><span class="line">    &#125;</span></pre></td></tr><tr><td class="code"><pre><span class="line"></span></pre></td></tr><tr><td class="code"><pre><span class="line">    <span class="function">String <span class="title">getTBIndex</span><span class="params">(<span class="keyword">int</span> v)</span> </span>&#123;</span></pre></td></tr><tr><td class="code"><pre><span class="line">        <span class="keyword">int</span> m = v % (dbNum * tbNum);</span></pre></td></tr><tr><td class="code"><pre><span class="line">        <span class="keyword">int</span> d = m % tbNum;</span></pre></td></tr><tr><td class="code"><pre><span class="line">        <span class="keyword">return</span> String.valueOf(d);</span></pre></td></tr><tr><td class="code"><pre><span class="line">    &#125;</span></pre></td></tr><tr><td class="code"><pre><span class="line">&#125;</span></pre></td></tr></table></figure>

<p>BaseComplexShardingAlgorithm.java</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">package</span> com.cd.common.core.sharding;</span></pre></td></tr><tr><td class="code"><pre><span class="line"></span></pre></td></tr><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> io.shardingsphere.api.algorithm.sharding.ListShardingValue;</span></pre></td></tr><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> io.shardingsphere.api.algorithm.sharding.ShardingValue;</span></pre></td></tr><tr><td class="code"><pre><span class="line"></span></pre></td></tr><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> java.util.ArrayList;</span></pre></td></tr><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> java.util.Collection;</span></pre></td></tr><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> java.util.List;</span></pre></td></tr><tr><td class="code"><pre><span class="line"></span></pre></td></tr><tr><td class="code"><pre><span class="line"><span class="comment">/**</span></span></pre></td></tr><tr><td class="code"><pre><span class="line"><span class="comment"> * description: 混合分片策略</span></span></pre></td></tr><tr><td class="code"><pre><span class="line"><span class="comment"> */</span></span></pre></td></tr><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">BaseComplexShardingAlgorithm</span> <span class="keyword">extends</span> <span class="title">BaseShardingAlgorithm</span> </span>&#123;</span></pre></td></tr><tr><td class="code"><pre><span class="line"></span></pre></td></tr><tr><td class="code"><pre><span class="line">    <span class="function">List&lt;String&gt; <span class="title">getDBNames</span><span class="params">(List&lt;String&gt; dbNames, Collection&lt;String&gt; allDBNames, Collection values)</span> </span>&#123;</span></pre></td></tr><tr><td class="code"><pre><span class="line">        <span class="keyword">for</span> (Object o : values) &#123;</span></pre></td></tr><tr><td class="code"><pre><span class="line">            String index = getDBIndex(getLast4(o));</span></pre></td></tr><tr><td class="code"><pre><span class="line">            <span class="keyword">for</span> (String db : allDBNames) &#123;</span></pre></td></tr><tr><td class="code"><pre><span class="line">                <span class="keyword">if</span> (db.endsWith(index)) &#123;</span></pre></td></tr><tr><td class="code"><pre><span class="line">                    dbNames.add(db);</span></pre></td></tr><tr><td class="code"><pre><span class="line">                    <span class="keyword">break</span>;</span></pre></td></tr><tr><td class="code"><pre><span class="line">                &#125;</span></pre></td></tr><tr><td class="code"><pre><span class="line">            &#125;</span></pre></td></tr><tr><td class="code"><pre><span class="line">        &#125;</span></pre></td></tr><tr><td class="code"><pre><span class="line">        <span class="keyword">return</span> dbNames;</span></pre></td></tr><tr><td class="code"><pre><span class="line">    &#125;</span></pre></td></tr><tr><td class="code"><pre><span class="line"></span></pre></td></tr><tr><td class="code"><pre><span class="line">    <span class="function">List&lt;String&gt; <span class="title">getTBNames</span><span class="params">(List&lt;String&gt; tbNames, Collection&lt;String&gt; allTBNames, Collection values)</span> </span>&#123;</span></pre></td></tr><tr><td class="code"><pre><span class="line">        <span class="keyword">for</span> (Object o : values) &#123;</span></pre></td></tr><tr><td class="code"><pre><span class="line">            String index = getTBIndex(getLast4(o));</span></pre></td></tr><tr><td class="code"><pre><span class="line">            <span class="keyword">for</span> (String db : allTBNames) &#123;</span></pre></td></tr><tr><td class="code"><pre><span class="line">                <span class="keyword">if</span> (db.endsWith(index)) &#123;</span></pre></td></tr><tr><td class="code"><pre><span class="line">                    tbNames.add(db);</span></pre></td></tr><tr><td class="code"><pre><span class="line">                    <span class="keyword">break</span>;</span></pre></td></tr><tr><td class="code"><pre><span class="line">                &#125;</span></pre></td></tr><tr><td class="code"><pre><span class="line">            &#125;</span></pre></td></tr><tr><td class="code"><pre><span class="line">        &#125;</span></pre></td></tr><tr><td class="code"><pre><span class="line">        <span class="keyword">return</span> tbNames;</span></pre></td></tr><tr><td class="code"><pre><span class="line">    &#125;</span></pre></td></tr><tr><td class="code"><pre><span class="line"></span></pre></td></tr><tr><td class="code"><pre><span class="line">    <span class="function">Collection <span class="title">getShardingValue</span><span class="params">(Collection&lt;ShardingValue&gt; shardingValues, <span class="keyword">final</span> String key)</span> </span>&#123;</span></pre></td></tr><tr><td class="code"><pre><span class="line">        Collection valueSet = <span class="keyword">new</span> ArrayList&lt;&gt;();</span></pre></td></tr><tr><td class="code"><pre><span class="line">        <span class="keyword">for</span> (ShardingValue next : shardingValues) &#123;</span></pre></td></tr><tr><td class="code"><pre><span class="line">            <span class="keyword">if</span> (next <span class="keyword">instanceof</span> ListShardingValue) &#123;</span></pre></td></tr><tr><td class="code"><pre><span class="line">                ListShardingValue value = (ListShardingValue) next;</span></pre></td></tr><tr><td class="code"><pre><span class="line">                <span class="keyword">if</span> (value.getColumnName().equals(key)) &#123;</span></pre></td></tr><tr><td class="code"><pre><span class="line">                    <span class="keyword">return</span> value.getValues();</span></pre></td></tr><tr><td class="code"><pre><span class="line">                &#125;</span></pre></td></tr><tr><td class="code"><pre><span class="line">            &#125;</span></pre></td></tr><tr><td class="code"><pre><span class="line">        &#125;</span></pre></td></tr><tr><td class="code"><pre><span class="line">        <span class="keyword">return</span> valueSet;</span></pre></td></tr><tr><td class="code"><pre><span class="line">    &#125;</span></pre></td></tr><tr><td class="code"><pre><span class="line"></span></pre></td></tr><tr><td class="code"><pre><span class="line">&#125;</span></pre></td></tr></table></figure>

<p>DoubleKeyDBShardingAlgorithm.java</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">package</span> com.cd.common.core.sharding;</span></pre></td></tr><tr><td class="code"><pre><span class="line"></span></pre></td></tr><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> io.shardingsphere.api.algorithm.sharding.ShardingValue;</span></pre></td></tr><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> io.shardingsphere.api.algorithm.sharding.complex.ComplexKeysShardingAlgorithm;</span></pre></td></tr><tr><td class="code"><pre><span class="line"></span></pre></td></tr><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> java.util.ArrayList;</span></pre></td></tr><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> java.util.Collection;</span></pre></td></tr><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> java.util.List;</span></pre></td></tr><tr><td class="code"><pre><span class="line"></span></pre></td></tr><tr><td class="code"><pre><span class="line"><span class="comment">/**</span></span></pre></td></tr><tr><td class="code"><pre><span class="line"><span class="comment"> * description: 双主键分片，分库策略。根据字段后四位计算</span></span></pre></td></tr><tr><td class="code"><pre><span class="line"><span class="comment"> * author: bowen</span></span></pre></td></tr><tr><td class="code"><pre><span class="line"><span class="comment"> */</span></span></pre></td></tr><tr><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">DoubleKeyDBShardingAlgorithm</span> <span class="keyword">extends</span> <span class="title">BaseComplexShardingAlgorithm</span> <span class="keyword">implements</span> <span class="title">ComplexKeysShardingAlgorithm</span> </span>&#123;</span></pre></td></tr><tr><td class="code"><pre><span class="line"></span></pre></td></tr><tr><td class="code"><pre><span class="line">    <span class="keyword">private</span> String key1;</span></pre></td></tr><tr><td class="code"><pre><span class="line">    <span class="keyword">private</span> String key2;</span></pre></td></tr><tr><td class="code"><pre><span class="line"></span></pre></td></tr><tr><td class="code"><pre><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">DoubleKeyDBShardingAlgorithm</span><span class="params">(String key1, String key2)</span> </span>&#123;</span></pre></td></tr><tr><td class="code"><pre><span class="line">        <span class="keyword">this</span>.key1 = key1;</span></pre></td></tr><tr><td class="code"><pre><span class="line">        <span class="keyword">this</span>.key2 = key2;</span></pre></td></tr><tr><td class="code"><pre><span class="line">    &#125;</span></pre></td></tr><tr><td class="code"><pre><span class="line"></span></pre></td></tr><tr><td class="code"><pre><span class="line">    <span class="meta">@Override</span></span></pre></td></tr><tr><td class="code"><pre><span class="line">    <span class="function"><span class="keyword">public</span> Collection&lt;String&gt; <span class="title">doSharding</span><span class="params">(Collection&lt;String&gt; collection, Collection&lt;ShardingValue&gt; shardingValues)</span> </span>&#123;</span></pre></td></tr><tr><td class="code"><pre><span class="line">        List&lt;String&gt; dbNames = <span class="keyword">new</span> ArrayList&lt;&gt;();</span></pre></td></tr><tr><td class="code"><pre><span class="line"></span></pre></td></tr><tr><td class="code"><pre><span class="line">        Collection key1Values = getShardingValue(shardingValues, <span class="keyword">this</span>.key1);</span></pre></td></tr><tr><td class="code"><pre><span class="line">        <span class="keyword">if</span> (key1Values != <span class="keyword">null</span> &amp;&amp; key1Values.size() &gt; <span class="number">0</span>) &#123;</span></pre></td></tr><tr><td class="code"><pre><span class="line">            <span class="keyword">return</span> getDBNames(dbNames, collection, key1Values);</span></pre></td></tr><tr><td class="code"><pre><span class="line">        &#125;</span></pre></td></tr><tr><td class="code"><pre><span class="line">        Collection key2Values = getShardingValue(shardingValues, <span class="keyword">this</span>.key2);</span></pre></td></tr><tr><td class="code"><pre><span class="line">        <span class="keyword">if</span> (key2Values != <span class="keyword">null</span> &amp;&amp; key2Values.size() &gt; <span class="number">0</span>) &#123;</span></pre></td></tr><tr><td class="code"><pre><span class="line">            <span class="keyword">return</span> getDBNames(dbNames, collection, key2Values);</span></pre></td></tr><tr><td class="code"><pre><span class="line">        &#125;</span></pre></td></tr><tr><td class="code"><pre><span class="line"></span></pre></td></tr><tr><td class="code"><pre><span class="line">        dbNames.addAll(collection);</span></pre></td></tr><tr><td class="code"><pre><span class="line">        <span class="keyword">return</span> dbNames;</span></pre></td></tr><tr><td class="code"><pre><span class="line">    &#125;</span></pre></td></tr><tr><td class="code"><pre><span class="line"></span></pre></td></tr><tr><td class="code"><pre><span class="line">&#125;</span></pre></td></tr></table></figure>

    </div>

    
    
    

      <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/SpringBoot/" rel="tag"># SpringBoot</a>
              <a href="/tags/Sharding-JDBC/" rel="tag"># Sharding-JDBC</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/algorithm/file-check/" rel="prev" title="文件校验">
      <i class="fa fa-chevron-left"></i> 文件校验
    </a></div>
      <div class="post-nav-item">
    <a href="/distributed/distributed-lock/" rel="next" title="分布式锁">
      分布式锁 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  

  </div>


          </div>
          

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#为什么要使用Sharding-JDBC"><span class="nav-number">1.</span> <span class="nav-text">为什么要使用Sharding-JDBC</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#Mycat和Sharding-JDBC选型"><span class="nav-number">1.1.</span> <span class="nav-text">Mycat和Sharding-JDBC选型</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#集成Sharding-JDBC"><span class="nav-number">2.</span> <span class="nav-text">集成Sharding-JDBC</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#遇到的问题"><span class="nav-number">3.</span> <span class="nav-text">遇到的问题</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#采用多数据源方式"><span class="nav-number">4.</span> <span class="nav-text">采用多数据源方式</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#yml配置"><span class="nav-number">4.1.</span> <span class="nav-text">yml配置</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#数据源配置"><span class="nav-number">4.2.</span> <span class="nav-text">数据源配置</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#主数据源"><span class="nav-number">4.2.1.</span> <span class="nav-text">主数据源</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Sharding数据源"><span class="nav-number">4.2.2.</span> <span class="nav-text">Sharding数据源</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#部分工具类"><span class="nav-number">4.3.</span> <span class="nav-text">部分工具类</span></a></li></ol></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="CXYZJP"
      src="/img/avatar.jpg">
  <p class="site-author-name" itemprop="name">CXYZJP</p>
  <div class="site-description" itemprop="description">记录生活中的点点滴滴</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">5</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">6</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <span class="exturl" data-url="aHR0cHM6Ly9naXRodWIuY29tL2N4eXpqcA==" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;cxyzjp"><i class="fa fa-fw fa-github"></i></span>
      </span>
      <span class="links-of-author-item">
        <span class="exturl" data-url="bWFpbHRvOjMyODEwODIyM0BxcS5jb20=" title="E-Mail → mailto:328108223@qq.com"><i class="fa fa-fw fa-envelope"></i></span>
      </span>
  </div>


  <div class="links-of-blogroll motion-element">
    <div class="links-of-blogroll-title">
      <i class="fa fa-fw fa-link"></i>
      友情链接
    </div>
    <ul class="links-of-blogroll-list">
        <li class="links-of-blogroll-item">
          <span class="exturl" data-url="aHR0cDovL2N4eXpqcC5jbg==" title="http:&#x2F;&#x2F;cxyzjp.cn">个人主页</span>
        </li>
        <li class="links-of-blogroll-item">
          <span class="exturl" data-url="aHR0cHM6Ly9naXRlZS5jb20vY3h5empwL2N4eXpqcC9wYWdlcw==" title="https:&#x2F;&#x2F;gitee.com&#x2F;cxyzjp&#x2F;cxyzjp&#x2F;pages">Gitee Pages</span>
        </li>
    </ul>
  </div>

      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

<div class="copyright">
  
  &copy; 2018 – 
  <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">CXYZJP</span>
</div>
  <div class="powered-by">由 <span class="exturl theme-link" data-url="aHR0cHM6Ly9oZXhvLmlv">Hexo</span> 强力驱动
  </div>
  <span class="post-meta-divider">|</span>
  <div class="theme-info">主题 – <span class="exturl theme-link" data-url="aHR0cHM6Ly9waXNjZXMudGhlbWUtbmV4dC5vcmc=">NexT.Pisces</span>
  </div>

        








        
      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>
  <script src="//cdn.jsdelivr.net/npm/medium-zoom@1/dist/medium-zoom.min.js"></script>
  <script src="//cdn.jsdelivr.net/npm/lozad@1/dist/lozad.min.js"></script>
<script src="/js/utils.js"></script>
<script src="/js/schemes/pisces.js"></script>
<script src="/js/next-boot.js"></script>



  




  <script src="/js/local-search.js"></script>













  

  

  

</body>
</html>
